package sv.com.renacempleo.web.controller.red;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.tuckey.web.filters.urlrewrite.utils.StringUtils;

import sv.com.renacempleo.dto.ctg.CtgCatalogo;
import sv.com.renacempleo.dto.red.RedDemandantes;
import sv.com.renacempleo.dto.red.RedObservacionesDemandante;
import sv.com.renacempleo.exception.WebException;
import sv.com.renacempleo.web.controller.BaseController;
import sv.com.renacempleo.web.util.DBContext;
import sv.com.renacempleo.web.util.WebUtilidades;
import sv.com.renacempleo.web.util.WebUtilidadesConstants;

@Controller
@RequestMapping("/admin/demandante")
public class RedDamandanteController extends BaseController{

	private static final long serialVersionUID = 5429557808764278652L;
	
	@RequestMapping(value = "/view", method = {RequestMethod.GET, RequestMethod.POST})
	public String view(ModelMap model, 
			@RequestParam (required = false) String header) {
		model.addAttribute(WebUtilidades.HEADER_TITLE, StringUtils.isBlank(header) ? "DEMANDANTES" : header);
		try {
			model.put("data", JSONArray.fromObject(DBContext.getRedDemandanteDao().findAllActivesAsArray()));
			model.put("ctgMunicipios", JSONArray.fromObject(DBContext.getCtgMunicipioDao().findAllActivesConcatNameDepAndMun()));
			model.put("ctgOficina", JSONArray.fromObject(DBContext.getCtgOficinasDao().findAllActivesAsArray()));
			model.put("sgdUsuario", JSONArray.fromObject(DBContext.getSgdUsuarioDao().findAllActivesAsArray()));
			model.put("ctgDocumento", JSONArray.fromObject(DBContext.getCtgDocumentosDao().findAllActiveByIdentificacion()));
			model.put("ctgDocumentoVigentes", JSONArray.fromObject(DBContext.getCtgDocumentosDao().findAllActiveByVigencia()));
			model.put("ctgGenero", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_GENERO_PADRE)));
			model.put("ctgEstadoCivil", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_ESTADO_CIVIL_PADRE)));
			model.put("ctgTipoLicencia", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_TIPO_LICENCIA_PADRE)));
			model.put("ctgTipoVehiculo",JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_TIPO_VEHICULO_PADRE)));
			model.put("ctgEscolaridad", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_ESCOLARIDAD_PADRE)));
			model.put("ctgEspecialidad", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_ESPECIALIDAD_PADRE)));
			model.put("ctgIdioma", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_IDIOMAS_PADRE)));
			model.put("ctgNivelIdioma", JSONArray.fromObject(DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidades.CTG_NIVEL_IDIOMA_PADRE)));
		} catch (WebException e) {
			logger.error("Exception:", e);
		}
		return "red/demandante/redDemandante";
	}
	
	@RequestMapping(value = "/consultarDemandante", method = {RequestMethod.POST})
	public void consultarDemandante(
			@RequestParam Long redDemandanteFolio, 
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result.put("demandante", DBContext.getRedDemandanteDao().getDemandante(redDemandanteFolio));
			result.put(SUCCESS, true);
		} catch (WebException e) {
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	
	@RequestMapping(value = "/validateDocument", method = {RequestMethod.POST})
	public void validateDocument(
			@RequestParam Long ctgDocumentoId, 
			@RequestParam String redDemandanteNumeroDocumento,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			List<Object[]> list = DBContext.getRedDemandanteDao().findDemandanteByDocumento(ctgDocumentoId, redDemandanteNumeroDocumento);
			if(list.size()>0)
				result.put("validate", true);
			else
				result.put("validate", false);
				
			result.put(SUCCESS, true);
		} catch (WebException e) {
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		}catch(Exception e){
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/save", method = {RequestMethod.POST, RequestMethod.GET})
	public void save(
			HttpServletResponse response,
			@ModelAttribute("redDemandante") RedDemandantes redDemandante){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Date date = Calendar.getInstance().getTime();	
			SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
			String fechaRegistro = String.valueOf(format.format(date));;
			
			CtgCatalogo wkfEstadoSeguimiento = new CtgCatalogo();
			wkfEstadoSeguimiento.setCtgCatalogoId(new Long(107));
			redDemandante.setWkfEstadoSeguimiento(wkfEstadoSeguimiento);
			redDemandante.setSgdUsuario(WebUtilidades.getSgdUsuarioFromAcegi());
			redDemandante.setRedDemandanteFechaRegistro(fechaRegistro);
			DBContext.getRedDemandanteDao().save(redDemandante);
			
			result.put("demandante", JSONArray.fromObject(DBContext.getRedDemandanteDao().findAllActivesAsArray()));
			result.put(SUCCESS, true);
			result.put(MESSAGE, UPDATED_DATA);
		}catch (WebException e) {
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, e.getExceptionMessage());
		} catch (Exception e) {
			logger.error("Exception:", e);
			result.put(FAILURE, true);
			result.put(MESSAGE, DEFAULT_ERROR_MESSAGE);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/getCtgEstadoSeguimiento", method = {RequestMethod.GET, RequestMethod.POST})
	public void getCtgEstadoSeguimiento(HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result.put("ctgEstadoSeguimiento", JSONArray.fromObject(
					DBContext.getCtgCatalogoDao().findAllActivesByCodigoAsArray(WebUtilidadesConstants.WKF_ESTADO_SEGUIMIENTO_PADRE)));
		}catch (Exception e) {
			logger.error(e);
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/guardarObservacion", method = {RequestMethod.GET, RequestMethod.POST})
	public void guardarObservaciones(HttpServletResponse response,
			@ModelAttribute("redObservacionesDemandante") RedObservacionesDemandante redObservacionesDemandante){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			DBContext.getRedObservacionesDemandanteDao().save(redObservacionesDemandante);
			result.put("observacion", JSONArray.fromObject(DBContext.getRedObservacionesDemandanteDao().findAllObservacionesByDemandante(
					redObservacionesDemandante.getRedDemandante().getRedDemandanteFolio())));
		} catch (WebException e) {
			logger.error(e);
			result.put(MESSAGE, WebUtilidades.getExceptionMessage(e));
			result.put(FAILURE, true);
		}catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			result.put(MESSAGE, "Procesamiento Incorrecto");
			result.put(FAILURE, true);
		}
		result.put(MESSAGE, result.get(MESSAGE));
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/viewObservaciones", method = {RequestMethod.POST})
	public void viewObservaciones(@RequestParam Long redDemandanteFolio,
			HttpServletResponse response){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result.put("observacion", JSONArray.fromObject(DBContext.getRedObservacionesDemandanteDao().findAllObservacionesByDemandante(
					redDemandanteFolio)));
		}catch (WebException e) {
			logger.error(e);
			result.put(MESSAGE, WebUtilidades.getExceptionMessage(e));
			result.put(FAILURE, true);
		}catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			result.put(MESSAGE, "Procesamiento Incorrecto");
			result.put(FAILURE, true);
		}
		result.put(MESSAGE, result.get(MESSAGE));
		serializeObject(result, response);
	}
	

}
